package com.twb.fileCenter.util;

import com.twb.core.exception.ServiceException;
import com.twb.core.util.SpringUtil;
import com.twb.fileCenter.config.FileCenterProperties;
import com.twb.fileCenter.constants.FileCenterConstants;
import com.twb.fileCenter.entity.dto.ImportExcelDto;
import com.twb.fileCenter.entity.dto.UploadFilesDto;
import com.twb.fileCenter.ftp.FtpUtil;
import com.twb.fileCenter.sftp.SftpUtil;
import com.twb.system.entity.twbEnclosure.TwbEnclosure;
import com.twb.system.entity.twbEnclosure.vo.SaveTwbEnclosureVo;
import com.twb.system.service.ITwbEnclosureService;
import com.twb.system.service.impl.TwbEnclosureService;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * @ClassName UploadFileUtil
 * @Description 文件上传工具类
 * @author DSY
 * @date 2019年1月15日 上午11:52:17
 */
public class UploadFileUtil {

	/**
	 * @Title  uploadFile
	 * @Description 上传文件
	 * @param fileCenterProperties
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @author DSY
	 * @date 2019年1月15日 上午11:52:08
	 */
	public static List<UploadFilesDto> uploadFile(FileCenterProperties fileCenterProperties, HttpServletRequest request) throws UnsupportedEncodingException {

		request.setCharacterEncoding("UTF-8");

		List<UploadFilesDto> results = new ArrayList<UploadFilesDto>();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		String folder = request.getParameter("folder");

		if (StringUtils.isBlank(folder)) {
			// 避免前台没有传递这个参数的时候会报错
			folder = "temp";
		} else {
			// 中文转码（对应jsp：encodeURI("中文")）
			folder = URLDecoder.decode(folder, "UTF-8");
		}
		String fileServerPath = fileCenterProperties.getFileServerPath();
		if (StringUtils.isBlank(fileServerPath)) {
			// 当前WEB环境的上层目录
			fileServerPath = new File(request.getSession().getServletContext().getRealPath("/")).getParent();
		}
		String uploadPath = fileCenterProperties.getUploadPath();
		String fileServerUrl = fileCenterProperties.getFileServerUrl();
		String serverType = fileCenterProperties.getServerType();
		String realPath = fileServerPath + uploadPath + "/" + folder + "/";
		String thumbnailPath = fileServerPath + uploadPath + "/thumbnail/" + folder + "/";

		if (serverType.equals(FileCenterConstants.serverType.LOCAL)) {
			File up = new File(realPath);
			if (!up.exists()) {
				up.mkdirs();
			}
		}

		if(fileCenterProperties.isThumbnail()) {
			File up = new File(thumbnailPath);
			if(!up.exists()) {
				up.mkdirs();
			}
		}
		/** 页面控件的文件流* */
		MultipartFile file = null;
		Map<String, MultipartFile> map = multipartRequest.getFileMap();
		for (Iterator<String> i = map.keySet().iterator(); i.hasNext();) {
			UploadFilesDto dto = new UploadFilesDto();
			Object obj = i.next();
			file = (MultipartFile) map.get(obj);
			if (file != null) {
				// 文件类型
				String fileType = file.getContentType();
				// 取得当前上传文件的文件名称
				String originalFileName = file.getOriginalFilename();
				// 文件格式后缀
				String extName = FilenameUtils.getExtension(originalFileName);
				// 本地上传图片方式
				String fileName = UUID.randomUUID().toString().replace("-", "");

				File dest = new File(realPath + fileName + "." + extName);
				boolean success = false;
				boolean thumbnailCreated = false;
				try {
					// 生成缩略图
					if(fileCenterProperties.isThumbnail()&&fileType.contains("image")) {
						Thumbnails.of(file.getInputStream()).size(fileCenterProperties.getThumbnailWidth(), fileCenterProperties.getThumbnailHeight()).toFile(thumbnailPath + fileName + "." + extName);
						thumbnailCreated = true;
					}
					if (serverType.equals(FileCenterConstants.serverType.FTP)) {
						// 获取输入流，用于将文件上传ftp服务器
						InputStream inputStream = file.getInputStream();
						success = FtpUtil.uploadFile(realPath, fileName + "." + extName, inputStream);
						if(thumbnailCreated) {
							File thumbnailFile = new File(thumbnailPath + fileName + "." + extName);
							InputStream thumbnailStream = new FileInputStream(thumbnailFile);
							success = FtpUtil.uploadFile(thumbnailPath, fileName + "." + extName, thumbnailStream);
							thumbnailFile.deleteOnExit();
						}
					}else if (serverType.equals(FileCenterConstants.serverType.SFTP)) {
						// 获取输入流，用于将文件上传ftp服务器
						InputStream inputStream = file.getInputStream();
						success = SftpUtil.uploadFile(realPath, fileName + "." + extName, inputStream);
						if(thumbnailCreated) {
							File thumbnailFile = new File(thumbnailPath + fileName + "." + extName);
							InputStream thumbnailStream = new FileInputStream(thumbnailFile);
							success = SftpUtil.uploadFile(thumbnailPath, fileName + "." + extName, thumbnailStream);
							thumbnailFile.deleteOnExit();
						}
					} else {
						file.transferTo(dest);
						success = true;
					}
				} catch (Exception e) {
					throw new ServiceException(e.getMessage());
				}
				dto.setFileId(fileName);
				dto.setSuccess(success);
				dto.setFileType(fileType);
				dto.setPath(uploadPath + "/" + folder + "/" + fileName + "." + extName);
				dto.setUrl(fileServerUrl + uploadPath + "/" + folder + "/" + fileName + "." + extName);
				dto.setFilePath(dto.getUrl());
				dto.setNewName(fileName + "." + extName);
				dto.setOldName(originalFileName);
				if(thumbnailCreated) {
					dto.setThumbnailPath(uploadPath + "/thumbnail/" + folder + "/" + fileName + "." + extName);
					dto.setThumbnailUrl(fileServerUrl + uploadPath + "/thumbnail/" + folder + "/" + fileName + "." + extName);
				}
				// 附件保存到数据库
				if (fileCenterProperties.isUploadToDb()) {
					ITwbEnclosureService enclosureService = SpringUtil.getBean(TwbEnclosureService.class);
					SaveTwbEnclosureVo vo = new SaveTwbEnclosureVo();
					vo.setBasePath(dto.getPath());
					vo.setOrigName(dto.getOldName());
					vo.setName(dto.getNewName());
					vo.setFileType(dto.getFileType());
					vo.setFilePath(dto.getUrl());
					vo.setThumbnailBasePath(dto.getThumbnailPath());
					vo.setThumbnailFilePath(dto.getThumbnailUrl());

					vo.setBizType(request.getParameter("bizType"));
					vo.setBizTypeName(request.getParameter("bizTypeName"));

					TwbEnclosure result = enclosureService.saveTwbEnclosure(vo);
					String fileId = result.getId();
					dto.setFileId(fileId);
				}
				results.add(dto);
			}
		}
		return results;
	}
	
	/**
	 * @Title uploadImportExcelFile
	 * @Description 上传导入Excel文件
	 * @param fileCenterProperties
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @author DHL
	 * @date 2021年8月9日 下午1:56:55
	 */
	public static ImportExcelDto uploadImportExcelFile(FileCenterProperties fileCenterProperties, HttpServletRequest request) throws UnsupportedEncodingException {

		request.setCharacterEncoding("UTF-8");
		
		String folder = "uploadExcel";

		ImportExcelDto results = new ImportExcelDto();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		if (StringUtils.isBlank(folder)) {
			// 避免前台没有传递这个参数的时候会报错
			folder = "temp";
		} else {
			// 中文转码（对应jsp：encodeURI("中文")）
			folder = URLDecoder.decode(folder, "UTF-8");
		}
		
		String fileServerPath = fileCenterProperties.getFileServerPath();
		if (StringUtils.isBlank(fileServerPath)) {
			// 当前WEB环境的上层目录
			fileServerPath = new File(request.getSession().getServletContext().getRealPath("/")).getParent();
		}
		
		String uploadPath = fileCenterProperties.getUploadPath();
		
		String serverType = fileCenterProperties.getServerType();
		
		String realPath = fileServerPath + uploadPath + "/" + folder + "/";

		if (serverType.equals(FileCenterConstants.serverType.LOCAL)) {
			File up = new File(realPath);
			if (!up.exists()) {
				up.mkdirs();
			}
		}

		/** 页面控件的文件流* */
		MultipartFile file = null;
		Map<String, MultipartFile> map = multipartRequest.getFileMap();
		for (Iterator<String> i = map.keySet().iterator(); i.hasNext();) {
			Object obj = i.next();
			file = (MultipartFile) map.get(obj);
			if (file != null) {
				
				// 取得当前上传文件的文件名称
				String originalFileName = file.getOriginalFilename();
				
				// 文件格式后缀
				String extName = FilenameUtils.getExtension(originalFileName);
				
				// 本地上传图片方式
				String fileName = UUID.randomUUID().toString().replace("-", "");

				File dest = new File(realPath + fileName + "." + extName);
				boolean success = false;
				try {
					if (serverType.equals(FileCenterConstants.serverType.FTP)) {
						// 获取输入流，用于将文件上传ftp服务器
						InputStream inputStream = file.getInputStream();
						success = FtpUtil.uploadFile(realPath, fileName + "." + extName, inputStream);
					} else if (serverType.equals(FileCenterConstants.serverType.SFTP)) {
						// 获取输入流，用于将文件上传ftp服务器
						InputStream inputStream = file.getInputStream();
						success = SftpUtil.uploadFile(realPath, fileName + "." + extName, inputStream);
					} else {
						file.transferTo(dest);
						success = true;
					}
				} catch (Exception e) {
					success = false;
				}
				
				if(success) {
					String fileServerUrl = fileCenterProperties.getFileServerUrl();
					
					results.setImportName(originalFileName);
					results.setImportPath(uploadPath + "/" + folder + "/" + fileName + "." + extName);
					results.setImportFilePath(fileServerUrl + results.getImportPath());
				}
			}
		}
		return results;
	}
}
